<template>
  <!-- 忘记密码 -->
  <router-link class="flex justify-between text-[#e54c5f]" to="/settings">
    <div class="flex items-center cursor-pointer">
      <el-icon>
        <ArrowLeftBold />
      </el-icon>
      <p class="pl-5">{{ $t("修改密码") }}</p>
    </div>
  </router-link>
  <el-card class="my-5">
    <el-form
      ref="formRef"
      :model="form"
      status-icon
      :rules="rules"
      label-position="right"
      label-width="150px"
    >
      <el-form-item prop="current_password" :label="$t('旧密码')">
        <el-input
          v-model="form.current_password"
          :placeholder="$t('请输入旧密码')"
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="new_password" :label="$t('新密码')">
        <el-input
          type="password"
          v-model="form.new_password"
          :placeholder="$t('请输入新密码')"
          show-password
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="again_password" :label="$t('确认密码')">
        <el-input
          type="password"
          v-model="form.again_password"
          :placeholder="$t('输入确认密码')"
          show-password
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="code" :label="$t('验证码')">
        <div class="flex items-center justify-between flex-1">
          <el-input
            v-model="form.code"
            :placeholder="$t('验证码')"
            size="large"
          >
          </el-input>

          <el-button
            size="large"
            plain
            type="primary"
            class="w-40 ml-4"
            @click="handleCaptcha"
            v-if="!codesms.disabled"
          >
            {{ $t("获取验证码") }}
          </el-button>
          <el-button
            size="large"
            type="primary"
            class="w-40 ml-4"
            v-else
            disabled
          >
            {{ codesms.count }}{{ $t("秒后重新获取") }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="justify-around flex-1 my-5 text-left">
          <el-button
            type="primary"
            size="large"
            class="w-48"
            @click="onSubmit"
            :loading="loading"
          >
            {{ $t("提交") }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { reactive, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { ChangeNewPassword, emailSendApi } from "@/api/login/index";
import { useUserStore } from "@/store/modules/user";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const formRef = ref("");
const form = reactive({
  current_password: "",
  new_password: "",
  again_password: "",
  code: "",
});
const loading = ref(false);

const router = useRouter();

const useUser = useUserStore();

const codesms = reactive({
  disabled: false,
  total: 60,
  count: 0,
});

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error(t("输入确认密码")));
  } else if (value !== form.new_password) {
    callback(new Error(t("确认密码和新密码一致")));
  } else {
    callback();
  }
};
// 校验
const rules = computed(() => {
  return {
    current_password: [
      { required: true, message: t("请输入旧密码"), trigger: "blur" },
    ],
    new_password: [
      { required: true, message: t("请输入新密码"), trigger: "blur" },
    ],
    again_password: [
      { required: true, validator: validatePass2, trigger: "blur" },
    ],
    code: [{ required: true, message: t("请输入验证码"), trigger: "blur" }],
  };
});
// 倒计时
const timerHandle = () => {
  codesms.count = codesms.total;
  codesms.disabled = true;

  let timer = setInterval(() => {
    if (codesms.count > 1 && codesms.count <= codesms.total) {
      codesms.count--;
    } else {
      codesms.disabled = false;
      clearInterval(timer);
    }
  }, 1000);
};

//发送验证码
const handleCaptcha = async () => {
  try {
    timerHandle();

    const res = await emailSendApi({
      email: useUser.userInfo.userName,
      code_type: "change_password",
    });
    ElMessage({
      type: "success",
      message: t("发送验证码成功"),
    });
    // console.log(res);
  } catch (error) {}
};

//修改密码
const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      try {
        loading.value = true;
        // 1.调用修改密码接口
        const res = await ChangeNewPassword(form);
        ElMessage({
          message: t("修改密码成功"),
          type: "success",
        });

        useUser.clearUserInfo();
        router.replace("/login");
      } catch (error) {
        loading.value = false;
      }
    })
    .catch((error) => {
      loading.value = false;
      // console.log(error);
    });
};
</script>
